package cn.bocweb.spinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.QaCheckBean;
import cn.bocweb.spinning.model.Bean.QaappDetailBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.adapter.QuestionDetailAdapter;
import cn.bocweb.spinning.view.common.BaseActivity;
import de.greenrobot.event.EventBus;

public class QuestionDetailActivity extends BaseActivity implements View.OnClickListener {

    QuestionDetailAdapter adapter;
    UserPresenter mPresenter;
    int page = 1, replySum;
    boolean isLastPage = false, isRefresh = false;
    List<QaappDetailBean.ReplyBean> mReplyBeen;
    String id, userid;
    int state;
    QaappDetailBean.DataBean mDataBean;
    boolean activityResult;
    boolean answerSubmit;
    int position;

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.question_response)
    RecyclerView questionResponse;
    @Bind(R.id.btn_answer)
    Button btnAnswer;
    @Bind(R.id.view_stone)
    View viewStone;
    @Bind(R.id.detail_pay)
    TextView mDetailPay;
    @Bind(R.id.detail_content)
    TextView mDetailContent;
    @Bind(R.id.img1)
    ImageView mImg1;
    @Bind(R.id.img2)
    ImageView mImg2;
    @Bind(R.id.img3)
    ImageView mImg3;
    @Bind(R.id.img4)
    ImageView mImg4;
    @Bind(R.id.img5)
    ImageView mImg5;
    @Bind(R.id.img6)
    ImageView mImg6;
    @Bind(R.id.img_layout)
    LinearLayout mImgLayout;
    @Bind(R.id.detail_time)
    TextView mDetailTime;
    @Bind(R.id.detail_answer_count)
    TextView mDetailAnswerCount;
    @Bind(R.id.ques_refresh)
    SwipeRefreshLayout mQuesRefresh;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_detail);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        userid = dataEntity.getUserid();

        mReplyBeen = new ArrayList<>();
        adapter = new QuestionDetailAdapter(mReplyBeen);
        mPresenter = new UserPresenterImp();

        initIntent();
        initList();
        initClickBtn();
        initToolbar();
        initImgDetail();
    }

    private void initImgDetail() {
        mImg1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(QuestionDetailActivity.this, ImgDetailActivity.class);
                    intent.putStringArrayListExtra(Constant.IMG_DETAIL_URL, (ArrayList<String>) mDataBean.getPhoto());
                    startActivity(intent);
                } catch (Exception e) {

                }
            }
        });

        mImg2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(QuestionDetailActivity.this, ImgDetailActivity.class);
                    intent.putStringArrayListExtra(Constant.IMG_DETAIL_URL, (ArrayList<String>) mDataBean.getPhoto());
                    startActivity(intent);
                } catch (Exception e) {

                }
            }
        });

        mImg3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new Intent(QuestionDetailActivity.this, ImgDetailActivity.class);
                    intent.putStringArrayListExtra(Constant.IMG_DETAIL_URL, (ArrayList<String>) mDataBean.getPhoto());
                    startActivity(intent);
                } catch (Exception e) {

                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constant.BACK_ANSWER_QA) {
            mReplyBeen.clear();
            adapter.notifyDataSetChanged();
            page = 1;
            isLastPage = false;
            isRefresh = false;
            mPresenter.qaDetail(id, page);
            activityResult = true;
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_answer: {
                intent = new Intent(this, WriteAnswerActivity.class);
                intent.putExtra(Constant.TO_QUES_DETAIL_ANSWER, id);
                intent.putExtra(Constant.TO_QUES_DETAIL_ANSWER_NUM, replySum);
                startActivityForResult(intent, Constant.BACK_ANSWER_QA);
            }
        }
    }

    public void onEventMainThread(QaappDetailBean bean) {
        if (mQuesRefresh.isRefreshing()) {
            mQuesRefresh.setRefreshing(false);
        }
        if (bean.getReturn_code() == 0) {
            if (bean.getData().getPhoto() == null) {
                mImgLayout.setVisibility(View.GONE);
            } else {
                mImgLayout.setVisibility(View.VISIBLE);
            }
            replySum = bean.getReplySum();
            mDataBean = bean.getData();
            if (!isRefresh) {
                if (state != Constant.QUESTION_DETAIL_MINE) {
                    String nickname;
                    if (TextUtils.isEmpty(bean.getData().getNickname())) {
                        nickname = new StringBuffer("未命名用户").append("的问题").toString();
                    } else {
                        nickname = new StringBuffer(bean.getData().getNickname()).append("的问题").toString();
                    }
                    toolbar.setTitle(nickname);

                } else {
                    toolbar.setTitle("我的问题");
                }
                if (bean.getData().getPhoto() != null) {
                    initImage(bean);
                }
                mDetailContent.setText(bean.getData().getContent());
                mDetailPay.setText(bean.getData().getScore());
                mDetailTime.setText(
                        DeviceUtil.getTimeByTwoTimeStampForPhp(
                                Long.parseLong(bean.getData().getTimeline()) * 1000,
                                System.currentTimeMillis()));
                mDetailAnswerCount.setText(String.valueOf(bean.getReplySum()));
                if (bean.getReply() != null) {
                    mReplyBeen.addAll(bean.getReply());
                    adapter.notifyDataSetChanged();
                }
            } else {
                if (bean.getReply() != null) {
                    mReplyBeen.addAll(bean.getReply());
                    adapter.notifyDataSetChanged();
                    isRefresh = false;
                }
            }
        } else if (bean.getReturn_code() == -202) {
            isLastPage = true;
            DeviceUtil.MyToast(this, "已经是最后一页");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(QaCheckBean bean) {
        if (bean.getReturn_code() == 0) {
            adapter.setSubmit(true);
            adapter.notifyDataSetChanged();
            answerSubmit = true;
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }

    private void initClickBtn() {
        btnAnswer.setOnClickListener(this);
    }

    private void initIntent() {
        Intent intent = getIntent();
        position = intent.getIntExtra(Constant.TO_QA_DETAIL_POSITION, 0);
        state = intent.getIntExtra(Constant.QUESTION_DETAIL, 0);
        id = intent.getStringExtra(Constant.TO_QA_DETAIL);
        initButton(state);
        mPresenter.qaDetail(id, page);
    }

    private void initButton(int state) {
        switch (state) {
            case Constant.QUESTION_DETAIL_MINE: {
                btnAnswer.setVisibility(View.GONE);
                viewStone.setVisibility(View.GONE);
                adapter.setMine(true);
            }
            default: {

            }
        }
    }


    private void initToolbar() {
        toolbar.setNavigationIcon(R.mipmap.btn_exit);
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (activityResult) {
                    setResult(
                            Constant.QUES_DETAIL_BACK_QUES_LIST,
                            new Intent().putExtra(
                                    "isAcivity",
                                    activityResult));
                } else if (answerSubmit) {
                    setResult(
                            Constant.QUES_DETAIL_BACK_MY_QUES,
                            new Intent().putExtra(
                                    "isSubmit",
                                    position));
                }
                finish();
            }
        });
    }

    private void initList() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        questionResponse.setAdapter(adapter);
        questionResponse.setLayoutManager(manager);

        adapter.setOnSubmitListener(new QuestionDetailAdapter.OnSubmitListener() {
            @Override
            public void click(String answer) {
                mPresenter.qaCheck(id, userid, answer);
            }
        });

        mQuesRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                isLastPage = false;
                isRefresh = true;
                mReplyBeen.clear();
                adapter.notifyDataSetChanged();
                mPresenter.qaDetail(id, page);
            }
        });


        questionResponse.addOnScrollListener(new RecyclerView.OnScrollListener() {
            boolean isSlidingToLast;

            //用来标记是否正在向最后一个滑动，既是否向右滑动或向下滑动
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                // 当不滚动时
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //获取最后一个完全显示的ItemPosition
                    int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                    int totalItemCount = manager.getItemCount();

                    // 判断是否滚动到底部，并且是向右滚动
                    if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                        //加载更多功能的代码
                        if (!isLastPage) {
                            page++;
                            mPresenter.qaDetail(id, page);
                        } else {
                            DeviceUtil.MyToast(QuestionDetailActivity.this, "已经是最后一页");
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if (dy > 0) {
                    //大于0表示，正在向右滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0 表示停止或向左滚动
                    isSlidingToLast = false;
                }

            }
        });
    }

    private void initImage(QaappDetailBean bean) {
        switch (bean.getData().getPhoto().size()) {
            case 0: {
                mImgLayout.setVisibility(View.GONE);
                break;
            }
            case 1: {
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(0))
                        .placeholder(R.mipmap.banner_empty)
                        .into(mImg1);
                break;
            }
            case 2: {
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(0))
                        .placeholder(R.mipmap.banner_empty)

                        .into(mImg1);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(1))
                        .placeholder(R.mipmap.banner_empty)

                        .into(mImg2);
                break;
            }
            case 3: {
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(0))
                        .placeholder(R.mipmap.banner_empty)

                        .into(mImg1);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(1))
                        .placeholder(R.mipmap.banner_empty)

                        .into(mImg2);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(2))
                        .placeholder(R.mipmap.banner_empty)

                        .into(mImg3);
                break;
            }
            case 4: {
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(0))
                        .into(mImg1);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(1))
                        .into(mImg2);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(2))
                        .into(mImg3);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(3))
                        .into(mImg4);
                break;
            }
            case 5: {
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(0))
                        .into(mImg1);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(1))
                        .into(mImg2);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(2))
                        .into(mImg3);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(3))
                        .into(mImg4);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(4))
                        .into(mImg5);
                break;
            }
            case 6: {
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(0))
                        .into(mImg1);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(1))
                        .into(mImg2);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(2))
                        .into(mImg3);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(3))
                        .into(mImg4);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(4))
                        .into(mImg5);
                Glide.with(this)
                        .load(bean.getData().getPhoto().get(5))
                        .into(mImg6);
                break;
            }
        }
    }

}
